﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.OleDb;
using System.Windows.Forms;
using System.Diagnostics;
using EncryptProject;

namespace CommonClass
{
    /// <summary>
    /// 主要是数据操作类，实例化数据连接，数据操作
    /// </summary>
    public class DataOperation
    {
        #region 常量

        // TreeNode
        public const string QUERY_GET_TREENODEDATA_BYSTATUS = "select * from TreeNode where Status = {0}"; // Tree 加载
        public const string QUERY_GET_TREENODEDATA = @"select ID, ParentID, TreeName, TreeText, DriverName, DriverPwd, DriverPort, ExceptChannel, 
switch(DriverType = 'DH', '大华', DriverType = 'HK', '海康', true, '其它') as DriverType, 
iif(Status = 1, '启用', '未启用') as Status
from TreeNode where ParentID <> '0' order by ID desc"; // Table 加载
        public const string QUERY_GET_ALLTREENODEDATA = "select * from TreeNode where ParentID <> '0' order by ID desc"; // 新增时
        public const string QUERY_GET_TREENODEDATA_BYID = "select * from TreeNode where ID = {0}"; // 修改时
        public const string QUERY_DELETE_TREENODE_BYID = "delete from TreeNode where ID = {0}"; // 删除时


        // WallInformation
        public const string QUERY_GET_ALLWALLDATA_BYWALLINDEX = "select * from WallInformation where WallIndex = {0} order by WallIndex, PanelIndex"; // 查询时
        public const string QUERY_GET_ALLWALLDATA = "select * from WallInformation order by WallIndex, PanelIndex"; // 新增时
        public const string QUERY_DELETE_WALL_BYWALLINDEX = "delete from WallInformation where WallIndex = {0};"; // 删除时


        // SystemInformation
        public const string SYSTEM_GUID = "FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF";
        public const string QUERY_GET_ALLSYSTEMDATA_BYID = "select * from SystemInformation where ID = '{0}'"; // 查询时，修改时


        // UserInformation
        public const string QUERY_GET_ALLUSERDATA = "select * from UserInformation"; // 查询时


        // ResetInformation
        public const string QUERY_GET_ALLRESETDATA = "select * from ResetInformation"; // 查询时


        // Region
        public const string QUERY_GET_ALLREGIONDATA = "select * from Region";
        public const string QUERY_GET_ALLREGIONDATA_BYREGIONID = "select * from Region where RegionID = {0}";


        // Site
        public const string QUERY_GET_ALLSITEDATA = "select * from Site";
        public const string QUERY_GET_ALLSITEDATA_BYREGIONID = "select * from Site where RegionID = '{0}'";
        public const string QUERY_GET_ALLSITEDATA_BYSITEID = "select * from Site where SiteID = {0}";


        // SiteEmployeeState
        public const string QUERY_GET_ALLEMPLOYEESTATEDATA_BYSITEID = "select * from SiteEmployeeState where SiteID = '{0}'";


        // Employee
        public const string QUERY_GET_ALLEMPLOYEEDATA = "select * from Employee";
        public const string QUERY_GET_ALLEMPLOYEEDATA_BYEMPID = "select * from Employee where EmpID = '{0}'";

        #endregion

        #region 变量

        DataConn dataCon = new DataConn(); // 连接数据库
        OleDbConnection oleDbCon; // 数据库连接

        #endregion

        #region 方法

        /// <summary>
        /// 执行 SQL 语句
        /// </summary>
        /// <param name="cmdText">查询的文本</param>
        /// <param name="connectionStringName">ConnectionString Name</param>
        /// <param name="mainProjectEXE">主工程可执行文件名称</param>
        /// <returns></returns>
        public int RunSqlCommand(string cmdText,
            string connectionStringName = null, string mainProjectEXE = null)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(connectionStringName) &&
                    string.IsNullOrWhiteSpace(mainProjectEXE))
                {
                    connectionStringName = "db_VWMSConnectionString";
                    mainProjectEXE = "MatrixManagement.exe";
                }

                OleDbCommand oleDbCom = GetDbCommand(cmdText,
                    connectionStringName, mainProjectEXE);
                oleDbCon.Open();
                return oleDbCom.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, Utilities.MSG_COMPANY);
                return 0;
            }
            finally
            {
                if (oleDbCon.State == ConnectionState.Open)
                {
                    oleDbCon.Close();
                }
            }
        }

        /// <summary>
        /// 获取数据集
        /// </summary>
        /// <param name="cmdText">查询的文本</param>
        /// <param name="tbName">数据表名称</param>
        /// <param name="connectionStringName">ConnectionString Name</param>
        /// <param name="mainProjectEXE">主工程可执行文件名称</param>
        /// <returns></returns>
        public DataSet GetDataSet(string cmdText, string tbName = null,
            string connectionStringName = null, string mainProjectEXE = null)
        {
            DataSet dataSet = new DataSet();

            try
            {
                if (string.IsNullOrWhiteSpace(connectionStringName) &&
                    string.IsNullOrWhiteSpace(mainProjectEXE))
                {
                    connectionStringName = "db_VWMSConnectionString";
                    mainProjectEXE = "MatrixManagement.exe";
                }

                OleDbDataAdapter oleDbAdapter = GetDataAdapter(cmdText,
                    connectionStringName, mainProjectEXE);

                if (string.IsNullOrWhiteSpace(tbName))
                    oleDbAdapter.Fill(dataSet);
                else
                    oleDbAdapter.Fill(dataSet, tbName);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, Utilities.MSG_COMPANY);
            }

            return dataSet;
        }

        /// <summary>
        /// 获取 DbCommand
        /// </summary>
        /// <param name="cmdText">查询的文本</param>
        /// <param name="connectionStringName">ConnectionString Name</param>
        /// <param name="mainProjectEXE">主工程可执行文件名称</param>
        /// <returns></returns>
        public OleDbCommand GetDbCommand(string cmdText,
            string connectionStringName = null, string mainProjectEXE = null)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(connectionStringName) &&
                    string.IsNullOrWhiteSpace(mainProjectEXE))
                {
                    connectionStringName = "db_VWMSConnectionString";
                    mainProjectEXE = "MatrixManagement.exe";
                }

                oleDbCon = dataCon.GetOleDbConnection(connectionStringName, mainProjectEXE);
                return new OleDbCommand(cmdText, oleDbCon);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, Utilities.MSG_COMPANY);
                return null;
            }
        }

        /// <summary>
        /// 获取 SqlDataAdapter
        /// </summary>
        /// <param name="cmdText">查询的文本</param>
        /// <param name="connectionStringName">ConnectionString Name</param>
        /// <param name="mainProjectEXE">主工程可执行文件名称</param>
        /// <returns></returns>
        public OleDbDataAdapter GetDataAdapter(string cmdText,
            string connectionStringName = null, string mainProjectEXE = null)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(connectionStringName) &&
                    string.IsNullOrWhiteSpace(mainProjectEXE))
                {
                    connectionStringName = "db_VWMSConnectionString";
                    mainProjectEXE = "MatrixManagement.exe";
                }

                oleDbCon = dataCon.GetOleDbConnection(connectionStringName, mainProjectEXE);
                return new OleDbDataAdapter(cmdText, oleDbCon);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, Utilities.MSG_COMPANY);
                return null;
            }
        }

        #region TreeNode 表操作

        /// <summary>
        /// 新增 TreeNode 项目
        /// </summary>
        /// <param name="treeText">设备别名</param>
        /// <param name="treeName">IP</param>
        /// <param name="driverName"></param>
        /// <param name="driverPwd"></param>
        /// <param name="driverPort"></param>
        /// <param name="exceptChannel"></param>
        /// <param name="status">1: 启用 | 0: 未启用</param>
        /// <param name="driverType"></param>
        /// <param name="connectionStringName">连接字符串数据库名称</param>
        /// <param name="mainProjectEXE">主工程可执行文件名称</param>
        /// <returns></returns>
        public int AddTreeNodeItem(string treeText, string treeName, string driverName, string driverPwd,
            string driverPort, string exceptChannel, int status, string driverType,
            string connectionStringName = null, string mainProjectEXE = null)
        {
            int resultCount = 0;
            DataSet dataSet = new DataSet();

            try
            {
                OleDbDataAdapter oleDbAdapter = GetDataAdapter(QUERY_GET_ALLTREENODEDATA,
                    connectionStringName, mainProjectEXE);
                new OleDbCommandBuilder(oleDbAdapter);
                oleDbAdapter.Fill(dataSet, "TreeNode");

                DataRow newRow = dataSet.Tables["TreeNode"].NewRow(); // 添加一个新数据行
                // 添加数据
                newRow["ParentID"] = 1;
                newRow["TreeName"] = treeName;
                newRow["TreeText"] = treeText;
                newRow["DriverName"] = driverName;
                newRow["DriverPwd"] = driverPwd;
                newRow["DriverPort"] = driverPort;
                newRow["ExceptChannel"] = exceptChannel;
                newRow["Status"] = status;
                newRow["DriverType"] = driverType;

                dataSet.Tables["TreeNode"].Rows.Add(newRow);
                resultCount = oleDbAdapter.Update(dataSet, "TreeNode");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, Utilities.MSG_COMPANY);
            }
            finally
            {
                dataSet.Dispose();
            }

            return resultCount;
        }

        /// <summary>
        /// 修改 TreeNode 项目
        /// </summary>
        /// <param name="id">主键</param>
        /// <param name="treeName">IP</param>
        /// <param name="treeText">设备别名</param>
        /// <param name="driverName"></param>
        /// <param name="driverPwd"></param>
        /// <param name="driverPort"></param>
        /// <param name="exceptChannel"></param>
        /// <param name="status">1: 启用 | 0: 未启用</param>
        /// <param name="driverType"></param>
        /// <param name="connectionStringName">连接字符串数据库名称</param>
        /// <param name="mainProjectEXE">主工程可执行文件名称</param>
        /// <returns></returns>
        public int EditTreeNodeItem(string id, string treeText,
            string treeName, string driverName, string driverPwd,
            string driverPort, string exceptChannel, int status, string driverType,
            string connectionStringName = null, string mainProjectEXE = null)
        {
            if (string.IsNullOrWhiteSpace(id))
            {
                MessageBox.Show("ID 不为空！", Utilities.MSG_COMPANY);
                return 0;
            }

            int resultCount = 0;
            DataSet dataSet = new DataSet();

            try
            {
                OleDbDataAdapter oleDbAdapter = GetDataAdapter(string.Format(QUERY_GET_TREENODEDATA_BYID, id),
                    connectionStringName, mainProjectEXE);
                new OleDbCommandBuilder(oleDbAdapter);
                oleDbAdapter.Fill(dataSet, "TreeNode");

                if (dataSet.Tables["TreeNode"].Rows.Count <= 0)
                    return resultCount;

                // 修改数据
                //dataSet.Tables["TreeNode"].Rows[0]["ParentID"] = 0;
                dataSet.Tables["TreeNode"].Rows[0]["TreeName"] = treeName;
                dataSet.Tables["TreeNode"].Rows[0]["TreeText"] = treeText;
                dataSet.Tables["TreeNode"].Rows[0]["DriverName"] = driverName;
                dataSet.Tables["TreeNode"].Rows[0]["DriverPwd"] = driverPwd;
                dataSet.Tables["TreeNode"].Rows[0]["DriverPort"] = driverPort;
                dataSet.Tables["TreeNode"].Rows[0]["ExceptChannel"] = exceptChannel;
                dataSet.Tables["TreeNode"].Rows[0]["Status"] = status;
                dataSet.Tables["TreeNode"].Rows[0]["DriverType"] = driverType;

                resultCount = oleDbAdapter.Update(dataSet, "TreeNode");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, Utilities.MSG_COMPANY);
            }
            finally
            {
                dataSet.Dispose();
            }

            return resultCount;
        }

        /// <summary>
        /// 根据 ID 删除 TreeNode 项目
        /// </summary>
        /// <param name="id">主键</param>
        /// <param name="connectionStringName">连接字符串数据库名称</param>
        /// <param name="mainProjectEXE">主工程可执行文件名称</param>
        /// <returns></returns>
        public int DeleteTreeNodeItem(string id,
            string connectionStringName = null, string mainProjectEXE = null)
        {
            if (string.IsNullOrWhiteSpace(id))
            {
                MessageBox.Show("ID 不为空！", Utilities.MSG_COMPANY);
                return 0;
            }

            try
            {
                string deleteSqlCmd = string.Format(QUERY_DELETE_TREENODE_BYID, id);
                return RunSqlCommand(deleteSqlCmd, connectionStringName, mainProjectEXE);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, Utilities.MSG_COMPANY);
                return 0;
            }
        }

        #endregion

        #region WallInformation 表操作

        /// <summary>
        /// 新增 WallInformation 项目
        /// </summary>
        /// <param name="wallIndex">大屏序号</param>
        /// <param name="panelIndex">视频窗口序号</param>
        /// <param name="ip"></param>
        /// <param name="port"></param>
        /// <param name="channel">所选通道号</param>
        /// <param name="userName"></param>
        /// <param name="userPwd"></param>
        /// <param name="type">设备类型</param>
        /// <returns></returns>
        public int AddWallItem(int wallIndex, int panelIndex,
            string ip, string port, string channel, string userName, string userPwd,
            string type)
        {
            int resultCount = 0;
            DataSet dataSet = new DataSet();

            try
            {
                OleDbDataAdapter oleDbAdapter = GetDataAdapter(QUERY_GET_ALLWALLDATA);
                new OleDbCommandBuilder(oleDbAdapter);
                oleDbAdapter.Fill(dataSet, "WallInformation");

                DataRow newRow = dataSet.Tables["WallInformation"].NewRow(); // 添加一个新数据行
                // 添加数据
                newRow["WallIndex"] = wallIndex;
                newRow["PanelIndex"] = panelIndex;
                newRow["IP"] = ip;
                newRow["Port"] = port;
                newRow["Channel"] = channel;
                newRow["UserName"] = userName;
                newRow["UserPwd"] = userPwd;
                newRow["Type"] = type;

                dataSet.Tables["WallInformation"].Rows.Add(newRow);
                resultCount = oleDbAdapter.Update(dataSet, "WallInformation");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, Utilities.MSG_COMPANY);
            }
            finally
            {
                dataSet.Dispose();
            }

            return resultCount;
        }

        /// <summary>
        /// 批量新增 WallInformation 项目
        /// </summary>
        /// <param name="wallList"></param>
        /// <returns></returns>
        public int AddWallItem(List<WallInformationModel> wallList)
        {
            if (wallList == null ||
                (wallList != null && wallList.Count <= 0))
            {
                MessageBox.Show("无数据添加！", Utilities.MSG_COMPANY);
                return 0;
            }

            int resultCount = 0;
            DataSet dataSet = new DataSet();

            try
            {
                OleDbDataAdapter oleDbAdapter = GetDataAdapter(QUERY_GET_ALLWALLDATA);
                new OleDbCommandBuilder(oleDbAdapter);
                oleDbAdapter.Fill(dataSet, "WallInformation");

                DataRow newRow;
                foreach (WallInformationModel wall in wallList)
                {
                    newRow = dataSet.Tables["WallInformation"].NewRow(); // 添加一个新数据行
                    // 添加数据
                    newRow["WallIndex"] = wall.WallIndex;
                    newRow["PanelIndex"] = wall.PanelIndex;
                    newRow["IP"] = wall.IP;
                    newRow["Port"] = wall.Port;
                    newRow["Channel"] = wall.Channel;
                    newRow["UserName"] = wall.UserName;
                    newRow["UserPwd"] = wall.UserPwd;
                    newRow["Type"] = wall.Type;

                    dataSet.Tables["WallInformation"].Rows.Add(newRow);
                }

                resultCount = oleDbAdapter.Update(dataSet, "WallInformation");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, Utilities.MSG_COMPANY);
            }
            finally
            {
                dataSet.Dispose();
            }

            return resultCount;
        }

        /// <summary>
        /// 根据 wallIndex 删除 WallInformation 项目
        /// </summary>
        /// <param name="wallIndex">大屏序号</param>
        /// <returns></returns>
        public int DeleteWallItem(int wallIndex)
        {
            if (wallIndex < 0)
            {
                MessageBox.Show("大屏序号错误！", Utilities.MSG_COMPANY);
                return 0;
            }

            try
            {
                string deleteSqlCmd = string.Format(QUERY_DELETE_WALL_BYWALLINDEX, wallIndex);
                return RunSqlCommand(deleteSqlCmd);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, Utilities.MSG_COMPANY);
                return 0;
            }
        }

        /// <summary>
        /// 批量根据 wallIndex 删除 WallInformation 项目
        /// </summary>
        /// <param name="wallIndexList">大屏序号组</param>
        /// <returns></returns>
        public int DeleteWallItem(List<int> wallIndexList)
        {
            if (wallIndexList == null ||
                (wallIndexList != null && wallIndexList.Count <= 0))
            {
                MessageBox.Show("无数据删除！", Utilities.MSG_COMPANY);
                return 0;
            }

            try
            {
                StringBuilder sbDeleteSqlCmd = new StringBuilder();
                string deleteSqlCmd;

                foreach (int wallIndex in wallIndexList)
                {
                    deleteSqlCmd = string.Format(QUERY_DELETE_WALL_BYWALLINDEX, wallIndex);
                    sbDeleteSqlCmd.Append(deleteSqlCmd);
                }

                return RunSqlCommand(sbDeleteSqlCmd.ToString());
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, Utilities.MSG_COMPANY);
                return 0;
            }
        }

        #endregion

        #region SystemInformation 表操作

        /// <summary>
        /// 新增 SystemInformation 项目
        /// </summary>
        /// <param name="machineNum">机器码</param>
        /// <param name="mendTime">补锁时间</param>
        /// <param name="softKeyID">加密锁唯一编号</param>
        /// <param name="trialTimes">试用次数</param>
        /// <param name="token">令牌</param>
        /// <returns></returns>
        public int AddSystemItem(string softKeyID, string machineNum,
            string trialTimes, string token, string mendTime)
        {
            int resultCount = 0;
            DataSet dataSet = new DataSet();

            try
            {
                OleDbDataAdapter oleDbAdapter = GetDataAdapter(string.Format(QUERY_GET_ALLSYSTEMDATA_BYID, SYSTEM_GUID));
                new OleDbCommandBuilder(oleDbAdapter);
                oleDbAdapter.Fill(dataSet, "SystemInformation");

                DataRow newRow = dataSet.Tables["SystemInformation"].NewRow(); // 添加一个新数据行
                // 添加数据
                newRow["ID"] = SYSTEM_GUID;
                newRow["SoftKeyID"] = softKeyID;
                newRow["MachineNum"] = machineNum;
                newRow["TrialTimes"] = trialTimes;
                newRow["Token"] = token;
                newRow["MendTime"] = mendTime;

                dataSet.Tables["SystemInformation"].Rows.Add(newRow);
                resultCount = oleDbAdapter.Update(dataSet, "SystemInformation");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, Utilities.MSG_COMPANY);
            }
            finally
            {
                dataSet.Dispose();
            }

            return resultCount;
        }

        /// <summary>
        /// 修改 SystemInformation 项目
        /// </summary>
        /// <param name="softKeyID">加密锁唯一编号</param>
        /// <param name="machineNum">机器码</param>
        /// <param name="trialTimes">试用次数</param>
        /// <param name="token">令牌</param>
        /// <param name="mendTime">补锁时间</param>
        /// <returns></returns>
        public int EditSystemItem(string softKeyID, string machineNum,
            string trialTimes, string token, string mendTime)
        {
            int resultCount = 0;
            DataSet dataSet = new DataSet();

            try
            {
                OleDbDataAdapter oleDbAdapter = GetDataAdapter(string.Format(QUERY_GET_ALLSYSTEMDATA_BYID, SYSTEM_GUID));
                new OleDbCommandBuilder(oleDbAdapter);
                oleDbAdapter.Fill(dataSet, "SystemInformation");

                if (dataSet.Tables["SystemInformation"].Rows.Count <= 0)
                    return resultCount;

                // 修改数据
                dataSet.Tables["SystemInformation"].Rows[0]["SoftKeyID"] = softKeyID;
                dataSet.Tables["SystemInformation"].Rows[0]["MachineNum"] = machineNum;
                dataSet.Tables["SystemInformation"].Rows[0]["TrialTimes"] = trialTimes;
                dataSet.Tables["SystemInformation"].Rows[0]["Token"] = token;
                dataSet.Tables["SystemInformation"].Rows[0]["MendTime"] = mendTime;

                resultCount = oleDbAdapter.Update(dataSet, "SystemInformation");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, Utilities.MSG_COMPANY);
            }
            finally
            {
                dataSet.Dispose();
            }

            return resultCount;
        }

        /// <summary>
        /// 重置次数
        /// </summary>
        /// <param name="trialTimes">次数</param>
        /// <returns></returns>
        public int ResetTrialTimes(string trialTimes)
        {
            int resultCount = 0;
            DataSet dataSet = new DataSet();

            try
            {
                OleDbDataAdapter oleDbAdapter = GetDataAdapter(string.Format(QUERY_GET_ALLSYSTEMDATA_BYID, SYSTEM_GUID));
                new OleDbCommandBuilder(oleDbAdapter);
                oleDbAdapter.Fill(dataSet, "SystemInformation");

                if (dataSet.Tables["SystemInformation"].Rows.Count <= 0)
                    return resultCount;

                // 修改数据
                dataSet.Tables["SystemInformation"].Rows[0]["TrialTimes"] = trialTimes;
                resultCount = oleDbAdapter.Update(dataSet, "SystemInformation");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, Utilities.MSG_COMPANY);
            }
            finally
            {
                dataSet.Dispose();
            }

            return resultCount;
        }

        /// <summary>
        /// 保存最新数据到 SystemInformation 表中【新增 | 修改（drSystem["ID"] != null）】
        /// </summary>
        /// <param name="drSystem">SystemInformation 表的信息【只含唯一一条记录】</param>
        /// <param name="dataOperation">操作数据库</param>
        public int EditSystemItem(DataRow drSystem,
            DataOperation dataOperation = null)
        {
            int resultCount = 0;

            if (drSystem == null)
                return resultCount;

            if (dataOperation == null)
                dataOperation = new DataOperation();

            try
            {
                #region 初始值
                if (drSystem[RegistryOperation.SUBKEYNAME_MACHINENUM] == null ||
                    (drSystem[RegistryOperation.SUBKEYNAME_MACHINENUM] != null &&
                    string.IsNullOrWhiteSpace(drSystem[RegistryOperation.SUBKEYNAME_MACHINENUM].ToString()))) // 机器码
                {
                    if (string.IsNullOrWhiteSpace(Utilities.MachineCode))
                    {
                        #region 生成唯一机器码
                        Utilities.GenerateMachineCode();
                        #endregion
                    }

                    drSystem[RegistryOperation.SUBKEYNAME_MACHINENUM] = Utilities.MachineCode; // 生成唯一自定义机器码
                }

                if (drSystem[RegistryOperation.SUBKEYNAME_TRIALTIMES] == null ||
                    (drSystem[RegistryOperation.SUBKEYNAME_TRIALTIMES] != null &&
                    string.IsNullOrWhiteSpace(drSystem[RegistryOperation.SUBKEYNAME_TRIALTIMES].ToString()))) // 试用次数
                    drSystem[RegistryOperation.SUBKEYNAME_TRIALTIMES] = EncryptAlgorithmHelper.Encrypt2("0", Utilities.MachineCode);

                if (drSystem[RegistryOperation.SUBKEYNAME_TOKEN] == null ||
                    (drSystem[RegistryOperation.SUBKEYNAME_TOKEN] != null &&
                    string.IsNullOrWhiteSpace(drSystem[RegistryOperation.SUBKEYNAME_TOKEN].ToString()))) // 令牌
                    drSystem[RegistryOperation.SUBKEYNAME_TOKEN] = SoftKeyOperation.KEY_EPROM;
                #endregion

                if (drSystem["ID"] != null &&
                    !string.IsNullOrWhiteSpace(drSystem["ID"].ToString())) // 修改
                {
                    resultCount = dataOperation.EditSystemItem(drSystem[RegistryOperation.SUBKEYNAME_SOFTKEYID] != null ? drSystem[RegistryOperation.SUBKEYNAME_SOFTKEYID].ToString() : string.Empty,
                        drSystem[RegistryOperation.SUBKEYNAME_MACHINENUM] != null ? drSystem[RegistryOperation.SUBKEYNAME_MACHINENUM].ToString() : string.Empty,
                        drSystem[RegistryOperation.SUBKEYNAME_TRIALTIMES] != null ? drSystem[RegistryOperation.SUBKEYNAME_TRIALTIMES].ToString() : EncryptAlgorithmHelper.Encrypt2("0", Utilities.MachineCode),
                        drSystem[RegistryOperation.SUBKEYNAME_TOKEN] != null ? drSystem[RegistryOperation.SUBKEYNAME_TOKEN].ToString() : SoftKeyOperation.KEY_EPROM,
                        drSystem[RegistryOperation.SUBKEYNAME_MENDTIME] != null ? drSystem[RegistryOperation.SUBKEYNAME_MENDTIME].ToString() : string.Empty);
                }
                else // 新增
                {
                    resultCount = dataOperation.AddSystemItem(drSystem[RegistryOperation.SUBKEYNAME_SOFTKEYID] != null ? drSystem[RegistryOperation.SUBKEYNAME_SOFTKEYID].ToString() : string.Empty,
                        drSystem[RegistryOperation.SUBKEYNAME_MACHINENUM] != null ? drSystem[RegistryOperation.SUBKEYNAME_MACHINENUM].ToString() : string.Empty,
                        drSystem[RegistryOperation.SUBKEYNAME_TRIALTIMES] != null ? drSystem[RegistryOperation.SUBKEYNAME_TRIALTIMES].ToString() : EncryptAlgorithmHelper.Encrypt2("0", Utilities.MachineCode),
                        drSystem[RegistryOperation.SUBKEYNAME_TOKEN] != null ? drSystem[RegistryOperation.SUBKEYNAME_TOKEN].ToString() : SoftKeyOperation.KEY_EPROM,
                        drSystem[RegistryOperation.SUBKEYNAME_MENDTIME] != null ? drSystem[RegistryOperation.SUBKEYNAME_MENDTIME].ToString() : string.Empty);
                }
            }
            catch (System.Exception ex)
            {
#if DEBUG
                Debug.WriteLine(ex.Message);
#endif
            }

            return resultCount;
        }

        #endregion

        #region Region 表操作

        /// <summary>
        /// 修改 Region 项目
        /// </summary>
        /// <param name="id">主键</param>
        /// <param name="pictureURL">图片路径</param>
        /// <param name="connectionStringName">连接字符串数据库名称</param>
        /// <param name="mainProjectEXE">主工程可执行文件名称</param>
        /// <returns></returns>
        public int EditRegionItem(string id, string pictureURL,
            string connectionStringName = null, string mainProjectEXE = null)
        {
            if (string.IsNullOrWhiteSpace(id))
            {
                MessageBox.Show("ID 不为空！", Utilities.MSG_COMPANY);
                return 0;
            }

            int resultCount = 0;
            DataSet dataSet = new DataSet();

            try
            {
                OleDbDataAdapter oleDbAdapter = GetDataAdapter(string.Format(QUERY_GET_ALLREGIONDATA_BYREGIONID, id),
                    connectionStringName, mainProjectEXE);
                new OleDbCommandBuilder(oleDbAdapter);
                oleDbAdapter.Fill(dataSet, "Region");

                if (dataSet.Tables["Region"].Rows.Count <= 0)
                    return resultCount;

                // 修改数据
                dataSet.Tables["Region"].Rows[0]["RegionURL"] = pictureURL;

                resultCount = oleDbAdapter.Update(dataSet, "Region");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, Utilities.MSG_COMPANY);
            }
            finally
            {
                dataSet.Dispose();
            }

            return resultCount;
        }

        #endregion

        #region Site 表操作

        /// <summary>
        /// 批量修改 Site 项目，修改区域站点坐标信息
        /// </summary>
        /// <param name="siteList"></param>
        /// <param name="connectionStringName">连接字符串数据库名称</param>
        /// <param name="mainProjectEXE">主工程可执行文件名称</param>
        /// <returns></returns>
        public int EditSiteItem(Dictionary<string, System.Windows.Point> siteList,
            string connectionStringName = null, string mainProjectEXE = null)
        {
            if (siteList == null ||
                (siteList != null && siteList.Count <= 0))
            {
                MessageBox.Show("无数据添加！", Utilities.MSG_COMPANY);
                return 0;
            }

            int resultCount = 0;
            DataSet dataSet = new DataSet();

            try
            {
                OleDbDataAdapter oleDbAdapter = GetDataAdapter(QUERY_GET_ALLSITEDATA,
                    connectionStringName, mainProjectEXE);
                new OleDbCommandBuilder(oleDbAdapter);
                oleDbAdapter.Fill(dataSet, "Site");

                if (dataSet.Tables["Site"].Rows.Count <= 0)
                    return resultCount;

                foreach (KeyValuePair<string, System.Windows.Point> site in siteList)
                {
                    foreach (DataRow siteRow in dataSet.Tables["Site"].Rows)
                    {
                        if (site.Key == siteRow["SiteID"].ToString())
                        {
                            siteRow["X"] = site.Value.X;
                            siteRow["Y"] = site.Value.Y;

                            break;
                        }
                    }
                }

                resultCount = oleDbAdapter.Update(dataSet, "Site");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, Utilities.MSG_COMPANY);
            }
            finally
            {
                dataSet.Dispose();
            }

            return resultCount;
        }

        #endregion

        //////////////////////////////////////////////////////////////////////////

        #region UserInformation 表操作

        /// <summary>
        /// 新增 UserInformation 项目
        /// </summary>
        /// <param name="connectionStringName">连接字符串数据库名称</param>
        /// <param name="mainProjectEXE">主工程可执行文件名称</param>
        /// <param name="userName">用户名称信息</param>
        /// <param name="cpuID">CPU 序号</param>
        /// <param name="diskID">磁盘序号</param>
        /// <param name="companyMD5">用户传入的 MD5 值</param>
        /// <param name="projectGUID">项目 ID</param>
        /// <param name="softKeyID">加密锁唯一编号</param>
        /// <param name="machineNum">机器码</param>
        /// <param name="mendTime">补锁时间</param>
        /// <param name="manageTime">办理加密锁时间</param>
        /// <returns></returns>
        public int AddUserItem(string userName,
            string cpuID, string diskID, string companyMD5, string projectGUID, 
            string softKeyID, string machineNum,
            string mendTime, string manageTime,
            string connectionStringName = null, string mainProjectEXE = null)
        {
            if (string.IsNullOrWhiteSpace(connectionStringName) &&
                string.IsNullOrWhiteSpace(mainProjectEXE))
            {
                connectionStringName = "db_UserConnectionString";
                mainProjectEXE = "BindingKeyProject.exe";
            }

            int resultCount = 0;
            DataSet dataSet = new DataSet();

            try
            {
                OleDbDataAdapter oleDbAdapter = GetDataAdapter(string.Format(QUERY_GET_ALLUSERDATA),
                    connectionStringName, mainProjectEXE);
                new OleDbCommandBuilder(oleDbAdapter);
                oleDbAdapter.Fill(dataSet, "UserInformation");

                DataRow newRow = dataSet.Tables["UserInformation"].NewRow(); // 添加一个新数据行
                // 添加数据
                newRow["UserName"] = userName;
                newRow["CPUID"] = cpuID;
                newRow["DiskID"] = diskID;
                newRow["CompanyMD5"] = companyMD5;
                newRow["ProjectGUID"] = projectGUID;
                newRow["SoftKeyID"] = softKeyID;
                newRow["MachineNum"] = machineNum;
                newRow["MendTime"] = mendTime;
                newRow["ManageTime"] = manageTime;

                dataSet.Tables["UserInformation"].Rows.Add(newRow);
                resultCount = oleDbAdapter.Update(dataSet, "UserInformation");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, Utilities.MSG_COMPANY);
            }
            finally
            {
                dataSet.Dispose();
            }

            return resultCount;
        }

        #endregion

        #region ResetInformation 表操作

        /// <summary>
        /// 新增 ResetInformation 项目
        /// </summary>
        /// <returns></returns>
        public int AddResetItem()
        {
            int resultCount = 0;
            DataSet dataSet = new DataSet();

            try
            {
                OleDbDataAdapter oleDbAdapter = GetDataAdapter(string.Format(QUERY_GET_ALLRESETDATA));
                new OleDbCommandBuilder(oleDbAdapter);
                oleDbAdapter.Fill(dataSet, "ResetInformation");

                DataRow newRow = dataSet.Tables["ResetInformation"].NewRow(); // 添加一个新数据行
                // 添加数据
                newRow["ResetTime"] = DateTime.Now;

                dataSet.Tables["ResetInformation"].Rows.Add(newRow);
                resultCount = oleDbAdapter.Update(dataSet, "ResetInformation");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, Utilities.MSG_COMPANY);
            }
            finally
            {
                dataSet.Dispose();
            }

            return resultCount;
        }

        #endregion

        #endregion
    }
}
